package com.myblog.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myblog.common.lang.Result;
import com.myblog.entity.*;
import com.myblog.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    BlogService blogService;
    @Autowired
    TypeService typeService;
    @Autowired
    TagService tagService;
    @Autowired
    BlogTagsService blogTagsService;
    @Autowired
    UserService userService;
    @Autowired
    EssayService essayService;
    @Autowired
    ProjectService projectService;

    //博客管理，可以根据搜索条件，和分页要求，进行信息筛选
    @PostMapping("/getBlogs")
    public Result getBlogs(@RequestBody Map<String,String> map){

        /*
            两个可能需要的查询参数，4种状态，
            0,都没有
            1,有 title 没 typeId
            5,没 title 有 typeId
            6,都有
        */
        int condition = 0;//默认都没有
        String title = null;
        Long typeId = null;

        if(map.get("title")!=null){
            title = map.get("title");
            condition++;
        }
        if(map.get("typeId")!=null){
            typeId = Long.parseLong(map.get("typeId"));
            condition+=5;   //定一个大跨度，方便判断
        }
        // 0 1 5 6
        System.out.println("############################# 查询情况："+condition);

        //分页工具
        int pageNum = Integer.parseInt(map.get("pageNum"));
        int pageSize = Integer.parseInt(map.get("pageSize"));
        Page pageInfo = new Page(pageNum,pageSize);
        IPage pageData = null; //定义查询结果

        //条件筛选并查询
        switch (condition){
            case 0:{
                //都没有，则返回全部
                pageData = blogService.page(pageInfo, new QueryWrapper<Blog>().orderByDesc("create_time"));
                break;
            }
            case 1:{
                //有 title 没 typeId
                pageData = blogService.page(pageInfo,new QueryWrapper<Blog>().like("title",title).orderByDesc("create_time"));
                break;
            }
            case 5:{
                //没 title 有 typeId
                pageData = blogService.page(pageInfo,new QueryWrapper<Blog>().eq("type_id",typeId).orderByDesc("create_time"));
                break;
            }
            case 6:{
                //都有
                pageData = blogService.page(pageInfo,new QueryWrapper<Blog>().like("title",title).eq("type_id",typeId).orderByDesc("create_time"));
                break;
            }
        }

        //先定义博客列表
        List<Blog> blogList =  pageData.getRecords();
        //构建博客——分类对应map
        HashMap<Long, Type> blogTypeMap = new HashMap<>();
        //构建博客——标签对应map
        HashMap<Long,List<Tag>> blogTagsMap = new HashMap<>();
        for(Blog tempBlog : blogList){
            //获取对应的分类对象
            Type tempType = typeService.getById(tempBlog.getTypeId());
            //获得标签集合
            List<BlogTags> temTagIds = blogTagsService.list(new QueryWrapper<BlogTags>().eq("blogs_id",tempBlog.getId()));
            List<Tag> temTags = new ArrayList<>();
            for (BlogTags tempBT : temTagIds){
                //遍历获取到的 标签id，根据 id 将其标签对象存入
                Tag tempTag = tagService.getById(tempBT.getTagsId());
                temTags.add(tempTag);
            }
            //将其存入对应的 map 中
            blogTypeMap.put(tempBlog.getId(),tempType);
            blogTagsMap.put(tempBlog.getId(),temTags);
        }

        //需要返回的信息：博客列表，博客——分类名对应，博客——标签列表对应
        return Result.succ(MapUtil.builder()
                .put("pageData",pageData)
                .put("blogTypeMap",blogTypeMap)
                .put("blogTagsMap",blogTagsMap)
                .map());
    }

    @PostMapping("/usBlog")
    public Result updateOrSaveBlog(@RequestBody Blog blog){
        blogService.saveOrUpdate(blog);
        return Result.succ(blog);
    }

    //删除 blog-tag 数据
    @GetMapping("/deleteTag")
    public Result deleteTag(@RequestParam("blogId") long blogId, @RequestParam("tagId") long tagId){
        Map<String,Object> keys = new HashMap<>();
        keys.put("blogs_id",blogId);
        keys.put("tags_id",tagId);
        blogTagsService.removeByMap(keys);
        return Result.succ("操作成功");
    }

    //删除博客
    @GetMapping("delBlog")
    public Result deleteBlog(@RequestParam("id") long id){
        blogService.removeById(id);
        return Result.succ("操作成功");
    }

    //获取所有用户信息
    @GetMapping("/allUsers")
    public Result getAllUsers(){
        List<User> users = userService.list();
        return Result.succ(users);
    }

    //根据Id删除用户
    @GetMapping("/delUser")
    public Result deleteUser(@RequestParam("id") long id){
        userService.removeById(id);
        return Result.succ(id);
    }

    //根据Id修改用户权限
    @GetMapping("/changeState")
    public Result changeState(@RequestParam("id") long id){
        User user = userService.getById(id);
        if(user.getType().equals("1")){
            user.setType("0");
        }else {
            user.setType("1");
        }
        userService.saveOrUpdate(user);
        return Result.succ(user);
    }

    //添加新的 blog
    @PostMapping("/addNewBlog")
    public Result addNewBlog(@RequestBody Blog blog){
        blogService.saveOrUpdate(blog);
        return Result.succ(blog);
    }


    //删除类别
    @GetMapping("/delType")
    public Result deleteType(@RequestParam("id") long id){
        try {
            typeService.removeById(id);
            return Result.succ("操作成功");
        }catch (DataIntegrityViolationException e){
            //e.printStackTrace();
            return Result.fail("操作失败！");
        }
    }

    //新增类别
    @PostMapping("/saveOrUpdateType")
    public Result addNewType(@RequestBody Type newType){
        typeService.saveOrUpdate(newType);
        return Result.succ("操作成功");
    }


    //新增标签
    @PostMapping("/saveOrUpdateTag")
    public Result addNewType(@RequestBody Tag newTag){
        tagService.saveOrUpdate(newTag);
        return Result.succ(newTag);
    }

    //删除标签
    @GetMapping("/delTag")
    public Result deleteTag(@RequestParam("id") long id){
        try {
            tagService.removeById(id);
            return Result.succ("操作成功");
        }catch (DataIntegrityViolationException e){
            //e.printStackTrace();
            return Result.fail("操作失败！");
        }
    }




    //新增随笔
    @PostMapping("/saveOrUpdateEssay")
    public Result addNewEssay(@RequestBody Essay essay){
        essayService.saveOrUpdate(essay);
        return Result.succ("操作成功");
    }

    //删除随笔
    @GetMapping("/delEssay")
    public Result deleteEssay(@RequestParam("id") long id){
        try {
            essayService.removeById(id);
            return Result.succ("操作成功");
        }catch (DataIntegrityViolationException e){
            //e.printStackTrace();
            return Result.fail("操作失败！");
        }
    }


    //项目管理
    @PostMapping("/saveOrUpdateProject")
    public Result addNewProject(@RequestBody Project project){
        projectService.saveOrUpdate(project);
        return Result.succ("操作成功");
    }

    //删除项目
    @GetMapping("/delProject")
    public Result deleteProject(@RequestParam("id") long id){
        try {
            projectService.removeById(id);
            return Result.succ("操作成功");
        }catch (DataIntegrityViolationException e){
            //e.printStackTrace();
            return Result.fail("操作失败！");
        }
    }

    //更改用户信息
    @PostMapping("/updateUser")
    public Result updateUser(@RequestBody User user){
        userService.saveOrUpdate(user);
        return Result.succ("操作成功！");
    }

    //密码验证
    @GetMapping("/verify")
    public Result verifyPassword(@RequestParam("id") long id, @RequestParam("password") String password){
        //将密码加密，并与数据库的匹配
        User user = userService.getById(id);
        if(!user.getPassword().equals(SecureUtil.md5(password))){
            return Result.fail("密码不正确");
        }else {
            return Result.succ("密码验证通过！");
        }
    }


    //改变博客推荐状态
    @GetMapping("/changeRecommend")
    public Result changeRecommend(@RequestParam("id") long id){
        Blog blog = blogService.getById(id);
        blog.setRecommend(!blog.getRecommend());
        blogService.saveOrUpdate(blog);
        return Result.succ("操作成功！");
    }
}
